package auth

import (
	"fmt"
	"github.com/golang-jwt/jwt/v5"
	"strings"
	"time"
)

var signKey = []byte("hjhjgygug")
var alg = jwt.SigningMethodHS256
var expiredDuration = time.Hour

func Sign(user string, data map[string]interface{}) (sign string, err error) {
	claims := jwt.MapClaims{}
	if data != nil {
		claims = data
	}

	claims["user"] = user
	claims["exp"] = time.Now().Add(expiredDuration).Unix()

	token := jwt.New(alg)
	token.Claims = claims
	return token.SignedString(signKey)
}

func Parse(token string) (user string, err error) {
	token = strings.TrimPrefix(token, "Bearer ")
	parsedToken, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
		return signKey, nil
	}, jwt.WithValidMethods([]string{alg.Name}))

	if err != nil {
		return "", err
	}

	data, _ := parsedToken.Claims.(jwt.MapClaims)
	d, ok := data["user"]
	if !ok {
		return "", fmt.Errorf("token not valid: not find 'user'")
	}
	return d.(string), nil
}
